<?php
use com\gdl\common\dataobject\common\ResultDO; 
use com\gdl\newagk\interfaces\AdminUserServiceIf;
use com\gdl\newagk\dataobject\adminuser\UserDTO; 
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use MagicCrypt\MagicCrypt;
/**
 * Admin后台用户相关接口 
 * 此接口包含后台用户列表 修改 添加 相关接口
 */
class api_AdminUserService extends api_Abstract implements AdminUserServiceIf{

	//获取用户列表
	public function userList(UserDTO $user){
		$where = $user->data ?$user->data : "";
        $platformId =  $user->id ? gdl_lib_BaseUtils::getStr($user->id, 'int') : 0;
        $offset = $user->offset ? gdl_lib_BaseUtils::getStr($user->offset, 'int') : 0;
        $num = $user->num ? gdl_lib_BaseUtils::getStr($user->num, 'int') : 10;
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		# 需要用到的model
		$modelUserCompany = new model_newagk_usercompany(); # user_company
		$userCompanyModel = new model_newagk_user();
		$ucMeberModel = new model_agkuc_member();
		$ucUserMeberModel = new  model_agkuc_ucentermember(); 
		try{
			# 分页
			if($offset=='0') $offset=1;
            $rows = $num;
            $limit = ($offset - 1) * $rows . "," . $rows;
            $group = 'order by agk_user.userid desc limit '.$limit;
			
			//$condition = "isdelete=0 and admin_reg in ('{$where["admin_reg"]}')";
			//$filed = "id,userId,gdlUserId,platformId";
			//$userCompanyList = $modelUserCompany->select($condition,$filed)->items;
			//foreach($userCompanyList as $key=>$val){
			//	$userInStr[] = $val['userId'];
			//}
			# 找出user_company对应的agk_user用户
			//$userInStr = implode(",",$userInStr)?implode(",",$userInStr):[]; 
			//$userCondition = " agk_user.isdelete =0 and (agk_user.admin_reg in ('{$where["admin_reg"]}') or agk_user.userId in (".$userInStr.")) "; 
			
			
			# 总平台数据
			if($platformId==0 || empty($platformId)){
				# 此查询只针对物理删除
				$userCondition = 'agk_user.isdelete=0 and (c.isdelete=0 or c.isdelete is null) ';
			}else{ 
				# 子平台数据 以agk_user id为主
				$userCondition = "agk_user.isdelete=0 and ((c.isdelete=0 or c.isdelete is null) and c.admin_reg in ('{$where["admin_reg"]}')) ";
			}
			
			# 获取考场用户 只获取user_company数据
			if($where['basic']=='all'){
				if($platformId==0 || empty($platformId)){
					$userCondition = "agk_user.isdelete=0 and c.isdelete=0 ";
				}else{
					$userCondition = "agk_user.isdelete=0 and c.isdelete=0 and c.admin_reg in('{$where["admin_reg"]}')";
				}
				
			} 
			# 获取user用户数据 使用user作为分页依据
			$userFiled = "agk_user.userId,agk_user.gdlUserId,agk_user.userName,agk_user.realName,agk_user.idcard,agk_user.mobile,c.id,c.platformId,c.companyId,c.departmentId,c.departmentgroupId,c.specialtyId,c.position,c.platformStatus,c.status as companyStatus,agk_user.status as userStatus,c.photoCollect,c.vface,c.admin_reg,FROM_UNIXTIME(c.updateTime, '%Y年%m月%d日') as update_time,agk_user.birthday,agk_user.sex,agk_user.city,agk_user.county,agk_user.age,c.isdelete as cisdelete";
			
			//$userFiled = "agk_user.userId,  c.id,agk_user.realName";
			$leftJoin = [
                'agk_user_company as c' => 'agk_user.userId=c.userId',
            ];
			
			if(isset($where['liekName'])){ # 手机 姓名 身份证
                $userCondition.= " and (agk_user.mobile like '%".$where["liekName"]."%' or agk_user.idcard like '%".$where['liekName']."%' or agk_user.realName like '%".$where['liekName']."%') ";
            }
            if(isset($where['idcard'])){ # 身份证
                $userCondition.= " and agk_user.idcard=".$where["idcard"];
            }
            if(isset($where['truename'])){ #真实名
                $userCondition.= " and agk_user.realName=".$where["truename"];
            }
			
            if(isset($where['company_id'])){ # 公司id
                $userCondition.= " and c.companyId=".$where["company_id"];
            }
            if(isset($where['departmentId'])){#部门id
                $userCondition.= " and c.departmentId=".$where["departmentId"];
            }
            if(isset($where['departmentGroupId'])){ # 班组id
                $userCondition.= " and c.departmentgroupId=".$where["departmentGroupId"];
            }
            if(isset($where['groupId'])){ # 分组id
                $userCondition.= " and c.groupId=".$where["groupId"];
            }
            if(isset($where['position'])){ # 职位id
                $userCondition.= " and c.position=".$where["position"];
            }
            if(isset($where['spce'])){#专业id
                $userCondition.= " and c.specialtyId=".$where["spce"];
            }
            if(isset($where['status'])){#状态
				if($where['status']==1){
					$userCondition.= " and c.status=1 ";
				}
				if($where['status']==2){
					$userCondition.= " and c.status=0 ";
				}
				if($where['status']==3){
					$userCondition.= " and c.status=2 ";
				} 
				
            }
            if(isset($where['platformStatus'])){ # 平台状态
                $userCondition.= " and c.platformStatus=".$where["platformStatus"];
            }
            if(isset($where['vface'])){#是否通过审核
				# 未审核的状态是0 前端传过来得不到数据，所以前端未审核为5
				if($where['vface']==5){
					$userCondition.= " and c.vface=0 ";
				}else{
					$userCondition.= " and c.vface=".$where["vface"];
				}
                
            }
			if(isset($where['age'])){#0-20 需要切割
				$ageStr = explode("-",$where['age']);
                $userCondition.= " and (agk_user.age>=".$ageStr[0]." and agk_user.age<=".$ageStr[1].") ";
            }
			if(isset($where['sex'])){#0男 1女
				$sexStr = $where['sex'] ? gdl_lib_BaseUtils::getStr($where['sex'], 'int') : 0;			
				 
				if($sexStr==1){ # 1男 2女
					$userCondition.= " and agk_user.sex=0 ";
				}else{
					$userCondition.= " and agk_user.sex=1 ";
				}
                
            }
			if(isset($where['selectId'])){#选中 用于导出用户
				$userCondition.= " and (c.id in (".$where['selectId'].") or agk_user.userId in (".$where['selectId'].") )";
			} 
			# 取agk_user数据为主要数据 
			$userList = $userCompanyModel->select($userCondition,$userFiled,$group,'',$leftJoin)->items;

			//gdl_lib_BaseUtils::addLog(json_encode($userCompanyModel));
                        $userListCount = $userCompanyModel->select($userCondition,'count(agk_user.userId) as num','','',$leftJoin)->items;
			
			$userListData = $this->getCompanyAll($userList); # 获取公司相关信息 
			
			if($userListData){
				$result->data = $userListData;
                $result->code = 200;
                $result->message = $userListCount[0]['num'];
			}
		} catch (Exception $e) {
			$result->success = false;
			$result->code = $e->getCode();
			$result->message = $e->getMessage(); 
        }
        return $result; 
	}
    /**
     *  添加用户
     *  uc 为用户中心，用户登录取值于uc用户中心
	 */
     public function addUser(UserDTO $user){
		$platformId = $user->id ? gdl_lib_BaseUtils::getStr($user->id, 'int') : '0';
		$update = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : [];
		$result = new ResultDO();
		$result->success = true;
		$result->code = 400;
		$result->message = "添加失败";
		$result->data = [];
                # 需要用到的model 
                $ucUserModel = new model_agkuc_ucentermember(); # uc用户
                $ucMemberModel = new model_agkuc_member(); # uc member
                $userModel = new model_newagk_user(); # 安管控agk_user
                $userCompanyModel = new model_newagk_usercompany(); # 安管控 agk_user_company
                
		try{    
			# 插入到uc user的数据
			$insertUcUser = [];
			$insertUcUser['username'] = $update['username'].mt_rand(1000, 9999);
			$insertUcUser['truename'] = $update['truename'];
			$insertUcUser['passsalt'] = parent::random(8);
			$insertUcUser['password'] = parent::dpassword($update['password'], $insertUcUser['passsalt']);
			$insertUcUser['showpassword'] = $update['password'];
			$insertUcUser['mobile'] = $update['mobile'];
			$insertUcUser['idcard'] = $update['idcard'];
			$insertUcUser['reg_time'] = time();
			$insertUcUser['status'] = 1;
			$insertUcUser['type'] = 1;
			$insertUcUser['way'] = 1;
			$insertUcUser['account_type'] = 1;
			
			# 插入到ucMember的数据
			$insertUcMeber = [];
			# 插入到user的数据
			$insertUser = [];
			#插入到userCompany里的数据
			$insertUserCompany = [];
			$modelPlaform = new model_newagk_platform();
			$platformAdminReg = $modelPlaform->getInfoById($res['platformId'], 'admin_reg');
			# 总平台 只允许添加不存在的用户
			//$existWhere = ['idcard' => $update['idcard']];
			$existWhere = "status=1 and (idcard='".$update['idcard']."' or mobile='".$update['mobile']."')";
			//$existWhere = "status=1 and (idcard='".$update['idcard']."' or mobile='".$update['mobile']."')";
			$existRes = $ucUserModel->selectOne($existWhere, '*'); # 是否存在
			 
			if($platformId==0 || empty($platformId)){
				# 总平台不能重复插入uc数据
				if($existRes['idcard']==$update['idcard']){
					$result->code = 400;
					$result->message = "该身份证已注册";
					return $result;
				}
				if($existRes['mobile']==$update['mobile']){
					$result->code = 400;
					$result->message = "该手机号码已注册";
					return $result;
				}
				
				if ($existRes['id']) {
					$result->code = 400;
					$result->message = '注册失败，用户中心已存在该用户，请前往子平台添加该用户';
					return $result;
				
				}else{ 
					$ret = $ucUserModel->insert($insertUcUser);
						if($ret){ 
						
							$insertUcMeber = [
									'uid'=>$existRes['id']?$existRes['id']:"",
									'birthday'=>$update['birthday'],
									'sex'=>$update['sex'], # 0:男 1 女
									'city'=>$update['city'],
									'count'=>$update['county'],
									'age'=>$update['age'],
									'nickname' => $existRes['username']?$existRes['username']:$insertUcUser['username'],
									'reg_time' => time(), 'status' => 1,
									'last_login_role' => 1,
									'show_role' => 1,
							];
							$retMember = $ucMemberModel->insert($insertUcMeber);  
							# 往user里面丢数据 
							$insertUser = [
									'gdlUserId'=>$ret,
									'userName'=>$insertUcUser['username'],
									'realName'=>$insertUcUser['truename'],
									'idcard'=>$insertUcUser['idcard'],
									'mobile'=>$update['mobile'], 
									'admin_id'=>1, 
									'createTime'=>time(),
									'admin_reg'=>$update['admin_reg'],
									'status'=>$update['status'],
									'isdelete'=>0,
									'birthday'=>$update['birthday'],
									'sex'=>$update['sex'], # 0:男 1 女
									'city'=>$update['city'],
									'county'=>$update['county'],
									'age'=>$update['age'], 									
							];
							
							$userEmpty = $userModel->selectOne(['gdlUserId'=>$ret,'isdelete'=>0],"userId"); 
							
							if($userEmpty['userId']){
								   $result->message = "添加用户失败，该用户已存在于该平台";
								   $userResult = $userEmpty['userId'];
							}else{
									$userResult = $userModel->insert($insertUser); 
							} # end 往agk_user里丢 
							
							if($userResult){
								$result->message = "添加用户成功";
								$result->code = 200;
							}
						}
					
				}
				
			# 子平台添加用户
			}else{
				# uc不存在重新注册
				if (!$existRes['id']) {
						# uc不存在重新注册
						//$ret = $ucUserModel->insert($insert);
						$ret = $ucUserModel->insert($insertUcUser);
						if($ret){ 
							$insertUcMeber = [
									'uid'=>$existRes['id']?$existRes['id']:"",
									'birthday'=>$update['birthday'],
									'sex'=>$update['sex'], # 0:男 1 女
									'city'=>$update['city'],
									'count'=>$update['county'],
									'age'=>$update['age'],
									'nickname' => $existRes['username']?$existRes['username']:$update['username'],
									'reg_time' => time(), 
									'status' => 1,
									'last_login_role' => 1,
									'show_role' => 1,
							];
							$retMember = $ucMemberModel->insert($insertUcMeber);
						}	
				}else{
					$ret = $existRes['id'];
				}
				
				# 往agk_user里面丢数据 
				$insertUser = [
						'gdlUserId'=>$ret,
						'userName'=>$existRes['username']?$existRes['username']:$insertUcUser['username'],
						'realName'=>$existRes['truename']?$existRes['truename']:$insertUcUser['truename'],
						'idcard'=>$existRes['idcard']?$existRes['idcard']:$insertUcUser['idcard'],
						'mobile'=>$update['mobile']?$update['mobile']:$insertUcUser['mobile'],
						//'company'=>$update['company_name'],
						//'companyId'=>$update['company_id'],
						//'departmentId'=>$update['departmentid'],
						//'departmentgroupId'=>$update['departmentgroupid'],
						'admin_id'=>1,
						//'position'=>$update['position'], # 职位
						'createTime'=>time(),
						'admin_reg'=>$update['admin_reg'],
						'status'=>$update['status'],
						'isdelete'=>0,
						'birthday'=>$update['birthday'],
						'sex'=>$update['sex'], # 0:男 1 女
						'city'=>$update['city'],
						'county'=>$update['county'],
						'age'=>$update['age'], 
				];
				
				#and admin_reg='{$update['admin_reg']} # 一对多的关系
				$userEmpty = $userModel->selectOne(['gdlUserId'=>$ret,'isdelete'=>0],"userId"); 
				
				if(!empty($userEmpty['userId'])){
					$result->message = "添加用户失败，该用户已存在于该平台";
					$userResult = $userEmpty['userId'];
				}else{
					$userResult = $userModel->insert($insertUser);
				}
				
				# 插入user表成功再插入到userCompany 
				if($userResult){
					$insertUserCompany = [
							'userId'=>$userResult,
							'gdlUserId'=>$ret,
							'platformId'=>$platformId,
							'companyId'=>$update['company_id'],
							'contactPhone'=>$update['mobile'], # 如果这里的手机和uc的不同可能会影响登录
							'departmentId'=>$update['departmentid'],
							'departmentgroupId'=>$update['departmentgroupid'],
							'specialtyId'=>$update['specialty_id'],
							'position'=>$update['position'],
							'status'=>$update['status'],
							'vface'=>0, 
							'admin_reg'=>$update['admin_reg'],
							'updateTime'=>time(),
							'isdelete'=>0,
							'jobTitle'=>$update['job_title'], # 1 公司外勤 2 内勤
					];
					if(empty($userResult)){
						$result->message = "未获取到用户";
					}
					$results = $userCompanyModel->isUserCompanyExist($userResult, $platformId); 
					//$userCompanyEmpty = $userCompanyModel->selectOne("userid = '{$userResult}' and platform_id ='{$platformId}' and isdelete=0","id");
				 
					# 如果用户退出了平台就逻辑假删 再次找回来直接修改isdelete状态值，不需要重新插入
					if($results['id'] && $results['isdelete']==0){
							$result->message = "添加用户失败,用户已存在";
					}else{
						if($results['isdelete']==1 || $results['isdelete']=="1"){
							$updateCompany['isdelete'] = 0;
							$userCompanyId = $userCompanyModel->update(['id'=>$results['id']],$updateCompany); 
						}else{
							$userCompanyId = $userCompanyModel->insert($insertUserCompany); 
						} 
						if($userCompanyId){
								$result->message = "添加用户成功";
								$result->code = 200;
						}
					} 
					
				} 
			}# end platformId
		}catch(Exception $e){	
			$result->success = false;
			$result->code = 500;
			$result->message =  $e->getMessage();
		}
		return $result;
    }
     
  
    /**
     *  判断该用户是否存在
     */
    public function selectEmptyUser(UserDTO $user){
        $platformId = $user->id ? gdl_lib_BaseUtils::getStr($user->id, 'int') : '0'; # 平台id
		$idcard = $user->field ? gdl_lib_BaseUtils::getStr($user->field) : []; # 更具身份证去查询uc
		
		$result = new ResultDO();
		$result->success = true;
		$result->code = 400;
		$result->message = "没有找到该用户";
		$result->data = [];
		
		try{
			$ucModel = new model_agkuc_ucentermember();
			$ucMeberModel = new model_agkuc_member();
			$userModel  = new model_newagk_user();
			$userCompanyModel = new model_newagk_usercompany();
			$ucUserInfo = $ucModel->selectOne(['idcard'=>$idcard],"id,username,truename,mobile,idcard,showpassword");
			
			if(isset($ucUserInfo['id'])){
				$ucMeberInfo = $ucMeberModel->selectOne(['uid'=>$ucUserInfo],'birthday,city,sex,age');
				$userInfo = $userModel->selectOne(['idcard'=>$idcard,'isdelete'=>0],'birthday,city,county,sex,age,userName,realName,idcard,userId,mobile');
				$ucUserInfo['birthday'] = $userInfo['birthday'];
				$ucUserInfo['city'] = $userInfo['city'];
				$ucUserInfo['county'] = $userInfo['county'];
				$ucUserInfo['mobile'] = $userInfo['mobile'];
				$ucUserInfo['sex'] = $userInfo['sex'];
				$ucUserInfo['age'] = $userInfo['age'];
				$ucUserInfo['showpassword'] = $ucUserInfo['showpassword'];
				$ucUserInfo['isset'] = 0; # 0不存在 可以添加 1存在不能添加
				#如果存在继续查询user_company
				if($userInfo){
					$companywhere = "isdelete=0 and userId=".$userInfo['userId']." and platformId=".$platformId;
					$companyUser = $userCompanyModel->selectOne($companywhere, 'id,userId');
					if($companyUser['id']){
						$result->message = "该用户已存在与该平台，无法添加";
						$result->code = 200;
						$ucUserInfo['isset'] = 1;
						$result->data[] = $ucUserInfo;
						return $result;
					}
				} 
				$result->code = 200;
				$result->message = "该用户已存在";
				$result->data[] = $ucUserInfo;
			}
			
		}catch(Exception $e){
			$result->success = false;
			$result->code = 500;
			$result->message = $e->getMessage();
		}
		return $result;
    }
    /**
     *  修改用户
     */
    public function updateUser(UserDTO $user){
        $platformId = $user->id ? gdl_lib_BaseUtils::getStr($user->id, 'int') : '0'; # 平台id
		$data = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : []; # 更新的数据
		$userid = $data["userid"]?$data['userid'] : 0;
		$id = $data["id"]?$data['id'] : 0;
		$result = new ResultDO();
		$result->success = true;
		$result->code = 400;
		$result->message = "更新失败";
		$result->data = [];
		try{
			$userModel = new model_newagk_user();
            $companyModel = new model_newagk_usercompany();
			$ucModel = new model_agkuc_ucentermember();
            $meberModel = new model_agkuc_member();
			$ucUserInfo = $ucModel->selectOne("id='{$data['gdl_userid']}' or idcard='{$data['idcard']}'","id,username,truename,avatar,mobile,idcard,status"); # uc用户 
			
			$existWhere = "status=1 and mobile='".$data['mobile']."'";
			$exInfo = $ucModel->selectOne($existWhere,'mobile');
			# 逻辑有待商榷
			if($data['mobile']!=$ucUserInfo['mobile']){
				if($exInfo['mobile']==$data['mobile']){
					$result->code = 400;
					$result->message = "该手机号已被注册";
					return $result;
				}
			} 
			# admin 总平台
			$meberUpdate = [
				'truename'=>$data['truename'],
				'mobile'=>$data['mobile'],
				'idcard'=>$data['idcard'],
				'showpassword'=>$data['password'],
			]; 
			# 密码留空则不修改
			if(isset($data['password']) && !empty($data['password'])){
				$meberUpdate['passsalt'] = parent::random(8);
				$meberUpdate['password'] = parent::dpassword($data['password'], $meberUpdate['passsalt']);
			}
			$mberData = [
				'birthday'=>$data['birthday'],
				'sex'=>$data['sex'], # 0:男 1 女
				 'city'=>$data['city'],
				'count'=>$data['county'],
				'age'=>$data['age'],
			];          
			$userUpdateData = [ 
				'realName'=>$data['truename'],
				'idcard'=>$data['idcard'],
				'mobile'=>$data['mobile'],
				'birthday'=>$data['birthday'],
				'sex'=>$data['sex'], # 0:男 1 女
				'city'=>$data['city'],
				'county'=>$data['county'],
				'age'=>$data['age'],
			]; 
			# 如果有则不修改agk_user状态
			if(empty($id)){
				$userUpdateData['status'] = $data['status']?$data['status']:0;
			}
			$companyData = [
				'contactPhone'=>$data['mobile'],
				'status'=>$data['status'],
			];
			$companyData['companyId'] = $data['company_id'];  
			$companyData['departmentId'] = $data['departmentid'];
			$companyData['departmentgroupId'] = $data['departmentgroupid'];
			$companyData['jobTitle'] = $data['job_title'];
			$companyData['position'] = $data['position'];
			$companyData['specialtyId'] = $data['specialty_id'];
			$companyData['updateTime'] = time(); 
			if($platformId == 0 || empty($platformId)){
				# 修改 meber表
				$meberRet = $ucModel->update(['id'=>$data['gdl_userid']],$meberUpdate);
				# 修改user_meber
				$mberRet = $meberModel->update(['uid'=>$data['gdl_userid']],$mberData);
				# 修改user表
				$updateResult = $userModel->update(['userId'=>$userid],$userUpdateData);
				if(!empty($id) && $id!=0){
					# 修改company表 
					$companyRet = $companyModel->update(['id'=>$id],$companyData);
				}
				
				# 判断是否成功
				if($meberRet || $mberRet || $updateResult || isset($companyRet)){
					$result->message = "更新成功";
					$result->code = 200;
				}
			}else{
				# 修改 meber表
				$meberRet = $ucModel->update(['id'=>$data['gdl_userid']],$meberUpdate);
				# 修改user_meber
				$mberRet = $meberModel->update(['uid'=>$data['gdl_userid']],$mberData);
				# 修改user表
				$updateResult = $userModel->update(['userId'=>$userid],$userUpdateData);
				# 修改company表 
				if(!empty($id) && $id!=0){
					# 修改company表                                
					$companyRet = $companyModel->update(['id'=>$id],$companyData);
				} 
				# 判断是否成功
				if($meberRet || $mberRet || $updateResult || isset($companyRet)){
					$result->message = "更新成功";
					$result->code = 200;
				}
				
			} 
			
		}catch(Exception $e){
                    $result->success = false;
                    $result->code = 500;
                    $result->message = $e->getMessage();
		} 
		return $result;
    }
	/**
	* 用户详情
	*/
	public function userInfo(UserDTO $user){ 
		$platformId = $user->id ? gdl_lib_BaseUtils::getStr($user->id, 'int') : '0'; # 平台id
		$data = $user->data ?$user->data : ""; # 更新的数据
		$userid = $data["userid"]?$data['userid'] : 0;
		$gdl_userid = $data["gdl_userid"]?$data['gdl_userid'] : 0;
		$id = $data["id"]?$data['id'] : 0; # company_user id
		$result = new ResultDO();
		$result->success = true;
		$result->code = 400; 
		$result->message = "获取失败";
		$result->data = [];
		if(empty($userid) || empty($gdl_userid) ){
			$result->message = "缺少必要参数";
			return $result;
		}
		
		try{
			$ucMemberModel = new model_agkuc_ucentermember();
			$userModel = new model_newagk_user();
			$ucModel = new model_agkuc_member();
			$platformModel = new model_newagk_platform();
			$filed = "id,username,truename,showpassword,avatar,mobile,idcard,status,showpassword";
			$condition = "id='{$gdl_userid}'";
			$userInfo = $ucMemberModel->selectOne($condition,$filed);
			$ucInfo = $ucModel->selectOne("uid='{$userInfo['id']}'","sex,birthday,city,count,age"); 
			$ageUserInfo = $userModel->selectOne('userId='.$userid,'birthday,sex,city,county,age,userId,gdlUserId,idcard,status,mobile,userName,realName');  
			
			 if(!empty($id)&& $id!=0){ #查当前平台的
				$companyUserModel = new model_newagk_usercompany();
				$userModel = new model_newagk_user();
				
				$companyInfo = $companyUserModel->selectOne("id='{$id}'","id,userId,gdlUserId,platformId,companyId,departmentId,departmentgroupId,specialtyId,position,platformStatus,status,vface,photoCollect");
				$platformName = $platformModel->selectOne('id='.$companyInfo['platformId'],'adminRealname,reals');
				if($companyInfo){
					$users = [
						'id'=>$companyInfo['id']?$companyInfo['id']:0,
						'username'=>$userInfo['username'],
						'truename'=>$userInfo['truename'],
						'showpassword'=>$userInfo['showpassword'],
						'mobile'=>$userInfo['mobile'],
						'idcard'=>$userInfo['idcard'],
						'sex'=>$ageUserInfo['sex'],
						'birthday'=>$ageUserInfo['birthday'],
						'city'=>$ageUserInfo['city'],
						'count'=>$ageUserInfo['county'],
						'age'=>$ageUserInfo['age'],
						'company_id'=>$companyInfo['companyId'], 
						'departmentid'=>$companyInfo['departmentId'],
						'departmentgroupid'=>$companyInfo['departmentgroupId'],
						'specialty_id'=>$companyInfo['specialtyId'],
						'position'=>$companyInfo['position'],
						'specialty_id'=>$companyInfo['specialtyId'],
						'platform_status'=>$companyInfo['platformStatus'],
						'platformId'=>$companyInfo['platformId'],
						'platformName'=>$platformName['reals'],
						'status'=>$companyInfo['status'],
                        'vface'=>$companyInfo['vface'],
                        'photoCollect'=>$companyInfo['photoCollect'],
					];
				}else{
                    $users = [];
                }
				 
			}else{
				$users['id'] = $id;
				$users['showpassword'] = isset($userInfo['showpassword'])?$userInfo['showpassword']:123456;
				$users['truename'] = isset($userInfo['truename'])?$userInfo['truename']:$ageUserInfo['realName'];
				$users['mobile'] = isset($userInfo['mobile'])?$userInfo['mobile']:$ageUserInfo['mobile'];
				$users['idcard'] = isset($ageUserInfo['idcard'])?$ageUserInfo['idcard'] :"";
				$users['status'] = isset($ageUserInfo['status'])?$ageUserInfo['status'] :"";
				$users['gdlUserId'] = isset($ageUserInfo['gdlUserId'])?$ageUserInfo['gdlUserId'] :$gdl_userid;
				$users['userId'] = isset($ageUserInfo['userId'])?$ageUserInfo['userId'] :$userId;
				$users['sex'] = isset($ucInfo['sex'])? $ucInfo['sex']:$ageUserInfo['sex'];
				$users['birthday'] = isset($ucInfo['birthday'])?$ucInfo['birthday']:$ageUserInfo['birthday'];
				$users['city'] = isset($ucInfo['city'])?$ucInfo['city']:$ageUserInfo['city'];
				$users['count'] = isset($ucInfo['count'])?$ucInfo['count']:$ageUserInfo['county'];
				$users['age'] = isset($ucInfo['age'])?$ucInfo['age']:$ageUserInfo['age'];					
			}
			if($users){
				$result->message = "获取成功";
				$result->code = 200;
				$result->data[] = $users; 
			}
		}catch(Exception $ex){
			$result->success = false;
			$result->code = 500;
			$result->message = $ex->getMessage();
		}
		
		return $result;
	}
	/**
	* 修改留底照片
	*/
	public function editFace(UserDTO $user){
		$platformId = $user->id ? gdl_lib_BaseUtils::getStr($user->id, 'int') : '0'; # 平台id
		$data = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : []; # 更新的数据
		$userid = $data["id"]?$data['id'] : 0;
		$status = $data['statsu'] ? $data['statsu']: "";
		$text = $data['text']?$data['text']:"";
		$result = new ResultDO();
		$result->success = true;
		$result->code = 400;
		$result->message = "更新失败";
		$result->data = []; 
		if(empty($userid)) {
			$result->message = "缺少用户唯一标识";
			return $result;
		}
		try{
			$userCompanyModel = new model_newagk_usercompany();
			$updata = [
				'vface'=>$status?$status:0,
				'facetext'=>$text,
			];
			$ret = $userCompanyModel->update("id='{$userid}'", $updata);
			if($ret){
				$result->message = "修改成功";
				$result->code = 200;
			}
		}catch(Exception $ex){
			$result->success = false;
			$result->code = 500;
			$result->message = $ex->getMessage();
		}
		
		return $result;
	}
	/**
	* 删除该用户
	*/
	public function deleteUser(UserDTO $user){
		$platformId = $user->id ? gdl_lib_BaseUtils::getStr($user->id, 'int') : '0'; # 平台id
		$data = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : []; # 更新的数据
		$userid = $data["userid"]?$data['userid'] : 0;
		$gdl_userid = $data["gdl_userid"]?$data['gdl_userid'] : 0;
		$id = $data["id"]?$data['id'] : 0;
		$result = new ResultDO();
		$result->success = true;
		$result->code = 400;
		$result->message = "更新失败";
		$result->data = [];
		if(empty($id) || empty($userid) || empty($gdl_userid)){
			$result->message = "service缺少必要参数";
			return $result;
		}
		try{
			$ucMemberModel = new model_agkuc_ucentermember();
			
		}catch(Exception $ex){
			$result->success = false;
			$result->code = 500;
			$result->message = $ex->getMessage();
		}
		
		return $result;
	}
	/**
	* 修改用户状态
	* 告知app用户异常
	*/
	public function editStatus(UserDTO $user){
		$platformId = $user->id ? gdl_lib_BaseUtils::getStr($user->id, 'int') : '0'; # 平台id
		$data = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : []; # 更新的数据
		$identityId = $data["id"]?$data['id'] : ""; # 逗号分隔
		$info = $data['info']?$data['info']:"all"; #delete 删除 #disable禁用 all其他
		$result = new ResultDO();
		$result->success = true;
		$result->code = 400;
		$result->message = "推送失败";
		$result->data = [];
		
		if(empty($identityId)){
			$result->message = "没有相关参数";
			return $result;
		}
		try{
			$textInfo = "账号异常已强制退出";
			$identityIdArray = explode(",",$identityId);
			$jpush = new service_jpush(); 
			if($info=="delete"){
				$textInfo = "账号异常，已被管理员移除平台";
				$entStatus = 4; # 删除
			}
			if($info=="disable"){
				$textInfo = "账号异常，已被管理员禁用";
				$entStatus = 5; #禁用
			}
			$user_alias =[];
			foreach($identityIdArray as $key=>$val){
				if(!empty($val)){
					$user_alias[] = $val;
				}
			}
			$ident = implode(",",$user_alias)?implode(",",$user_alias):"0";
			$extras = ['extras'=>['overExam'=>$entStatus]]; # 附加参数
			//$extras = ['extras'=>['type'=>$info,'info'=>$textInfo,'identityId'=>$ident]]; # 附加参数
			$alias = $user_alias;  # 用户别名 用户idnetityid userCompany的id
			//不指定定标题第一个参数即为自定义消息
			$res = $jpush->jpushOneMessage('',$alias, $extras);  # 推送到指定用户
			if($res){
				$result->code = 200;
				$result->message = "推送成功";
			}

		}catch(Exception $ex){
			$result->success = false;
			$result->code = 500;
			$result->message = $ex->getMessage();
		}
		
		return $result;
	}
	/**
		获取相关参数
	*/
	public function getCompanyAll($userList){
		# 公司数据
		$companyModel = new model_newagk_company();
		$companyList = $companyModel->select(['isdelete'=>0,'status'=>1],'id,name,admin_reg')->items;
		# 部门和班组数据
		$departModel = new model_newagk_department();
		$departList = $departModel->select(['isdelete'=>0,'status'=>1],'id,name,admin_reg')->items;
		# 平台列表数据
		$platformModel = new model_newagk_platform();
		$platformList = $platformModel->select(['isdelete'=>0,'status'=>1],'id,name,reals,adminRealname,admin_reg')->items;
		# 专业和职位列表
		$spceModel = new model_newagk_specialty();
		$spceList = $spceModel->select(['isdelete'=>0,'status'=>1],'id,name,admin_reg')->items;
		#company用户id
		$userInId = [];
		for($i=0; $i<count($userList); $i++){
			$userList[$i]['re_platform'] = "总平台"; # 平台
			$userList[$i]['re_company'] = "--"; # 公司
			$userList[$i]['re_depart'] = "--"; # 部门
			$userList[$i]['re_departGroup'] = "--"; # 班组
			$userList[$i]['re_position'] = "--"; # 职位
			$userList[$i]['re_spce'] = "--"; # 专业
			
			$userList[$i]['status'] = $userList[$i]['userStatus']; #
			if(!empty($userList[$i]['id'])){
				$userList[$i]['status'] = $userList[$i]['companyStatus']; #
				$userList[$i]['re_platform'] = "--"; # 平台
				$userList[$i]['re_company'] = "--"; # 公司
				$userList[$i]['re_depart'] = "--"; # 部门
				$userList[$i]['re_departGroup'] = "--"; # 班组
				$userList[$i]['re_position'] = "--"; # 职位
				$userList[$i]['re_spce'] = "--"; # 专业
			}
			if(!empty($userList[$i]['photoCollect'])){
				$userList[$i]['photoCollect'] = $userList[$i]['photoCollect']."?imageMogr2/thumbnail/50x50";
			}
			
			# 平台
			if($platformList){
				for($j=0; $j<count($platformList); $j++){
					
					if($userList[$i]['platformId']==$platformList[$j]['id'] || $userList[$i]['admin_reg']==$platformList[$j]['admin_reg']){
						$userList[$i]['re_platform'] = $platformList[$j]['reals']; # 平台
					}
				}
			}
			# 公司
			if($companyList){
				for($k=0; $k<count($companyList); $k++){
					if($userList[$i]['companyId']==$companyList[$k]['id']){
						$userList[$i]['re_company'] = $companyList[$k]['name']; # 公司
					}
				}
			}
			# 部门和班组
			if($departList){
				for($y=0; $y<count($departList); $y++){
					if($userList[$i]['departmentId']==$departList[$y]['id']){
						$userList[$i]['re_depart'] = $departList[$y]['name']; # 部门
					} 
					if($userList[$i]['departmentgroupId']==$departList[$y]['id']){
						$userList[$i]['re_departGroup'] = $departList[$y]['name']; # 班组
					}
				}
			}
			# 专业和职位
			if($spceList){
				for($x=0; $x<count($spceList); $x++){
					if($userList[$i]['position']==$spceList[$x]['id']){
						$userList[$i]['re_position'] = $spceList[$x]['name']; # 职位
					}
					if($userList[$i]['specialtyId']==$spceList[$x]['id']){
						$userList[$i]['re_spce'] = $spceList[$x]['name']; # 专业
					}
				}
			}
			$userInId[] = $userList[$i]['userId'];
		} 
		return $userList;
	}
	
	/**
		根据身份证获取信息
	*/
	public function getIdcard($idcard){
		//通过身份证号查询出性别与生日 
		$strleng = strlen($idcard);
		$birth = strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8); 
		$getsex = substr($idcard, (strlen($idcard)==$strleng ? -2 : -1), 1) % 2 ? '1' : '0'; //1为男 2为女
		$births = substr($birth,0,4)."-".substr($birth,4,2)."-".substr($birth,6,2);
		$years = date("Y",time());
		$age = $years-substr($birth,0,4);
		$sex = 0;
		if($getsex==1){
			$sex = 0; //男
		}else{
			$sex = 1; //女
		}
		return ['birth'=>$births, 'sex'=>$sex,'age'=>$age];
	}
}

